/**
 * 
 */
package com.effectiv.req1.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.effectiv.req1.domain.Lov;
import com.effectiv.req1.domain.User;
import com.effectiv.req1.repository.UserRepository;

/**
 * @author Dhrubo
 *
 */
@Component
public class SimpleUserDetailsService implements UserDetailsService {
	
	@Autowired
	private UserRepository userRepository;

	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@Override
	public UserDetails loadUserByUsername(String email)
			throws UsernameNotFoundException {
		
		User user = userRepository.findByEmail(email);
		
		List<Lov> roles = user.getRoles();
		
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
		
		for(Lov r : roles){
			GrantedAuthority ga = new SimpleGrantedAuthority(r.getName());
			authorities.add(ga);
		}
		
		SimpleUserDetails userDetails = new SimpleUserDetails(user, authorities);
		
		return userDetails;
	}

}
